package com.lu.pojo.datastructures.queue;

/**
 * @author luzhenfang
 * @date 2020 05 31
 * @description 队列 数组模拟实现
 */
public class ArrayQueueDemo {
    public static void main(String[] args) {
        IQueue<Integer> queue = new ArrayQueue<>(10);
        IQueue<String> stringArrayQUeue = new ArrayQueue<>(3);
        try {
            queue.enQueue(1);
            queue.enQueue(2);
            queue.enQueue(3);
            queue.enQueue(4);
            queue.enQueue(5);
            System.out.println("HEAD:"+queue.getHead());
            for (int i = 0; i < 5; i++) {
                System.out.println(queue.deQueue());
            }


            stringArrayQUeue.enQueue("你");
            stringArrayQUeue.enQueue("真");
            stringArrayQUeue.enQueue("好");
            stringArrayQUeue.deQueue();

            for (int i = 0; i < 2; i++) {
                System.out.println(stringArrayQUeue.deQueue());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// 队列数据结构
class ArrayQueue<T> implements IQueue<T> {
    // 最大容量 队头 队尾 数组
    private int maxSize;
    private int front;
    private int rear;
    private Object[] arr;

    // 初始化队列
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new Object[maxSize];
        // 初始化
        front = rear = -1;
    }

    // 队列是否满
    public boolean isFull() {
        return rear == maxSize - 1;
    }

    @Override
    public void clearQueue() {
        arr=null;
        // 通知 jvm 来回收垃圾
        System.gc();
    }

    // 队列是否为空
    public boolean isEmpty() {
        return rear == front;
    }

    @Override
    public T getHead() throws Exception {
        if(isEmpty()){
            throw new Exception("队列已空,操作失败！");
        }
        return (T) arr[front+1];
    }

    // 入队
    @Override
    public void enQueue(T e) throws Exception {

        if (isFull()) {
            throw new Exception("队列已满,无法入队!");
        } else {
            arr[++rear] = e;
        }
    }

    // 出队
    public T deQueue() throws Exception {
        if (isEmpty()) {
            throw new Exception("队列已空,无法出队!");
        } else {
            return (T) arr[++front];
        }
    }
}
